home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 53 / PC Actual CD 53.iso / Share / Progra / python / BeOpen-Python-2.0.exe / COLORDB.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  8.8 KB  |  290 lines

  1. """Color Database.
  2.  
  3. This file contains one class, called ColorDB, and several utility functions.
  4. The class must be instantiated by the get_colordb() function in this file,
  5. passing it a filename to read a database out of.
  6.  
  7. The get_colordb() function will try to examine the file to figure out what the
  8. format of the file is.  If it can't figure out the file format, or it has
  9. trouble reading the file, None is returned.  You can pass get_colordb() an
  10. optional filetype argument.
  11.  
  12. Supporte file types are:
  13.  
  14.     X_RGB_TXT -- X Consortium rgb.txt format files.  Three columns of numbers
  15.                  from 0 .. 255 separated by whitespace.  Arbitrary trailing
  16.                  columns used as the color name.
  17.  
  18. The utility functions are useful for converting between the various expected
  19. color formats, and for calculating other color values.
  20.  
  21. """
  22.  
  23. import sys
  24. import string
  25. import re
  26. from types import *
  27. import operator
  28.  
  29. class BadColor(Exception):
  30.     pass
  31.  
  32. DEFAULT_DB = None
  33.  
  34.  
  35.  
  36. # generic class
  37. class ColorDB:
  38.     def __init__(self, fp):
  39.         lineno = 2
  40.         self.__name = fp.name
  41.     # Maintain several dictionaries for indexing into the color database.
  42.     # Note that while Tk supports RGB intensities of 4, 8, 12, or 16 bits, 
  43.     # for now we only support 8 bit intensities.  At least on OpenWindows, 
  44.     # all intensities in the /usr/openwin/lib/rgb.txt file are 8-bit
  45.     #
  46.     # key is (red, green, blue) tuple, value is (name, [aliases])
  47.     self.__byrgb = {}
  48.     #
  49.     # key is name, value is (red, green, blue)
  50.     self.__byname = {}
  51.     #
  52.         # all unique names (non-aliases).  built-on demand
  53.         self.__allnames = None
  54.     while 1:
  55.         line = fp.readline()
  56.         if not line:
  57.         break
  58.         # get this compiled regular expression from derived class
  59. ##            print '%3d: %s' % (lineno, line[:-1])
  60.         mo = self._re.match(line)
  61.         if not mo:
  62.         sys.stderr.write('Error in %s, line %d\n' % (fp.name, lineno))
  63.         lineno = lineno + 1
  64.         continue
  65.         #
  66.         # extract the red, green, blue, and name
  67.         #
  68.             red, green, blue = self._extractrgb(mo)
  69.             name = self._extractname(mo)
  70.         keyname = string.lower(name)
  71. ##            print keyname, '(%d, %d, %d)' % (red, green, blue)
  72.         #
  73.         # TBD: for now the `name' is just the first named color with the
  74.         # rgb values we find.  Later, we might want to make the two word
  75.         # version the `name', or the CapitalizedVersion, etc.
  76.         #
  77.         key = (red, green, blue)
  78.         foundname, aliases = self.__byrgb.get(key, (name, []))
  79.         if foundname <> name and foundname not in aliases:
  80.         aliases.append(name)
  81.         self.__byrgb[key] = (foundname, aliases)
  82.         #
  83.         # add to byname lookup
  84.         #
  85.         self.__byname[keyname] = key
  86.         lineno = lineno + 1
  87.  
  88.     # override in derived classes
  89.     def _extractrgb(self, mo):
  90.         return map(int, mo.group('red', 'green', 'blue'))
  91.  
  92.     def _extractname(self, mo):
  93.         return mo.group('name')
  94.  
  95.     def filename(self):
  96.         return self.__name
  97.  
  98.     def find_byrgb(self, rgbtuple):
  99.         """Return name for rgbtuple"""
  100.     try:
  101.         return self.__byrgb[rgbtuple]
  102.     except KeyError:
  103.         raise BadColor(rgbtuple)
  104.  
  105.     def find_byname(self, name):
  106.         """Return (red, green, blue) for name"""
  107.     name = string.lower(name)
  108.     try:
  109.         return self.__byname[name]
  110.     except KeyError:
  111.         raise BadColor(name)
  112.  
  113.     def nearest(self, red, green, blue):
  114.         """Return the name of color nearest (red, green, blue)"""
  115.     # TBD: should we use Voronoi diagrams, Delaunay triangulation, or
  116.     # octree for speeding up the locating of nearest point?  Exhaustive
  117.     # search is inefficient, but seems fast enough.
  118.     nearest = -1
  119.     nearest_name = ''
  120.     for name, aliases in self.__byrgb.values():
  121.         r, g, b = self.__byname[string.lower(name)]
  122.         rdelta = red - r
  123.         gdelta = green - g
  124.         bdelta = blue - b
  125.         distance = rdelta * rdelta + gdelta * gdelta + bdelta * bdelta
  126.         if nearest == -1 or distance < nearest:
  127.         nearest = distance
  128.         nearest_name = name
  129.     return nearest_name
  130.  
  131.     def unique_names(self):
  132.         # sorted
  133.         if not self.__allnames:
  134.             self.__allnames = []
  135.             for name, aliases in self.__byrgb.values():
  136.                 self.__allnames.append(name)
  137.             # sort irregardless of case
  138.             def nocase_cmp(n1, n2):
  139.                 return cmp(string.lower(n1), string.lower(n2))
  140.             self.__allnames.sort(nocase_cmp)
  141.         return self.__allnames
  142.  
  143.     def aliases_of(self, red, green, blue):
  144.         try:
  145.             name, aliases = self.__byrgb[(red, green, blue)]
  146.         except KeyError:
  147.             raise BadColor((red, green, blue))
  148.         return [name] + aliases
  149.     
  150.  
  151. class RGBColorDB(ColorDB):
  152.     _re = re.compile(
  153.         '\s*(?P<red>\d+)\s+(?P<green>\d+)\s+(?P<blue>\d+)\s+(?P<name>.*)')
  154.  
  155.  
  156. class HTML40DB(ColorDB):
  157.     _re = re.compile('(?P<name>\S+)\s+(?P<hexrgb>#[0-9a-fA-F]{6})')
  158.  
  159.     def _extractrgb(self, mo):
  160.         return rrggbb_to_triplet(mo.group('hexrgb'))
  161.  
  162. class LightlinkDB(HTML40DB):
  163.     _re = re.compile('(?P<name>(.+))\s+(?P<hexrgb>#[0-9a-fA-F]{6})')
  164.  
  165.     def _extractname(self, mo):
  166.         return string.strip(mo.group('name'))
  167.  
  168. class WebsafeDB(ColorDB):
  169.     _re = re.compile('(?P<hexrgb>#[0-9a-fA-F]{6})')
  170.  
  171.     def _extractrgb(self, mo):
  172.         return rrggbb_to_triplet(mo.group('hexrgb'))
  173.  
  174.     def _extractname(self, mo):
  175.         return string.upper(mo.group('hexrgb'))
  176.  
  177.  
  178.  
  179. # format is a tuple (RE, SCANLINES, CLASS) where RE is a compiled regular
  180. # expression, SCANLINES is the number of header lines to scan, and CLASS is
  181. # the class to instantiate if a match is found
  182.  
  183. FILETYPES = [
  184.     (re.compile('XConsortium'), RGBColorDB),
  185.     (re.compile('HTML'), HTML40DB),
  186.     (re.compile('lightlink'), LightlinkDB),
  187.     (re.compile('Websafe'), WebsafeDB),
  188.     ]
  189.  
  190. def get_colordb(file, filetype=None):
  191.     colordb = None
  192.     fp = open(file)
  193.     try:
  194.         line = fp.readline()
  195.         if not line:
  196.             return None
  197.         # try to determine the type of RGB file it is
  198.         if filetype is None:
  199.             filetypes = FILETYPES
  200.         else:
  201.             filetypes = [filetype]
  202.         for typere, class_ in filetypes:
  203.             mo = typere.search(line)
  204.             if mo:
  205.                 break
  206.         else:
  207.             # no matching type
  208.             return None
  209.         # we know the type and the class to grok the type, so suck it in
  210.         colordb = class_(fp)
  211.     finally:
  212.         fp.close()
  213.     # save a global copy
  214.     global DEFAULT_DB
  215.     DEFAULT_DB = colordb
  216.     return colordb
  217.  
  218.  
  219.  
  220. _namedict = {}
  221. def rrggbb_to_triplet(color, atoi=string.atoi):
  222.     """Converts a #rrggbb color to the tuple (red, green, blue)."""
  223.     global _namedict
  224.     rgbtuple = _namedict.get(color)
  225.     if rgbtuple is None:
  226.         if color[0] <> '#':
  227.             raise BadColor(color)
  228.     red = color[1:3]
  229.     green = color[3:5]
  230.     blue = color[5:7]
  231.     rgbtuple = (atoi(red, 16), atoi(green, 16), atoi(blue, 16))
  232.     _namedict[color] = rgbtuple
  233.     return rgbtuple
  234.  
  235.  
  236. _tripdict = {}
  237. def triplet_to_rrggbb(rgbtuple):
  238.     """Converts a (red, green, blue) tuple to #rrggbb."""
  239.     global _tripdict
  240.     hexname = _tripdict.get(rgbtuple)
  241.     if hexname is None:
  242.     hexname = '#%02x%02x%02x' % rgbtuple
  243.     _tripdict[rgbtuple] = hexname
  244.     return hexname
  245.  
  246.  
  247. _maxtuple = (256.0,) * 3
  248. def triplet_to_fractional_rgb(rgbtuple):
  249.     return map(operator.__div__, rgbtuple, _maxtuple)
  250.  
  251.  
  252. def triplet_to_brightness(rgbtuple):
  253.     # return the brightness (grey level) along the scale 0.0==black to
  254.     # 1.0==white
  255.     r = 0.299
  256.     g = 0.587
  257.     b = 0.114
  258.     return r*rgbtuple[0] + g*rgbtuple[1] + b*rgbtuple[2]
  259.  
  260.  
  261.  
  262. if __name__ == '__main__':
  263.     import string
  264.  
  265.     colordb = get_colordb('/usr/openwin/lib/rgb.txt')
  266.     if not colordb:
  267.     print 'No parseable color database found'
  268.     sys.exit(1)
  269.     # on my system, this color matches exactly
  270.     target = 'navy'
  271.     red, green, blue = rgbtuple = colordb.find_byname(target)
  272.     print target, ':', red, green, blue, triplet_to_rrggbb(rgbtuple)
  273.     name, aliases = colordb.find_byrgb(rgbtuple)
  274.     print 'name:', name, 'aliases:', string.join(aliases, ", ")
  275.     r, g, b = (1, 1, 128)              # nearest to navy
  276.     r, g, b = (145, 238, 144)              # nearest to lightgreen
  277.     r, g, b = (255, 251, 250)              # snow
  278.     print 'finding nearest to', target, '...'
  279.     import time
  280.     t0 = time.time()
  281.     nearest = colordb.nearest(r, g, b)
  282.     t1 = time.time()
  283.     print 'found nearest color', nearest, 'in', t1-t0, 'seconds'
  284.     # dump the database
  285.     for n in colordb.unique_names():
  286.         r, g, b = colordb.find_byname(n)
  287.         aliases = colordb.aliases_of(r, g, b)
  288.         print '%20s: (%3d/%3d/%3d) == %s' % (n, r, g, b,
  289.                                              string.join(aliases[1:]))
  290.